use crate::config::app_list::get_global_site_list_config;
use crate::config::app_list::init_global_site_list_config;
use crate::util::app_with_site_config::init_app_with_site_config_vec;
use crate::util::history_log::start_read_log;
use crate::util::history_log::start_update_history_log;
use crate::util::log_helper::push_dev;
use crate::{
  config::run_setup::RUN_SETUP_CONFIG, util::app_with_site_config::find_target_app_vec_by,
};
use util::clap_helper::clap_arg::build_clap_command;
use crate::util::log_helper::write_default_log;
use tokio::runtime::Runtime;

pub mod config;
pub mod util;

fn main() {
  let cmd_result = build_clap_command();
  let global_run_setup_config = &RUN_SETUP_CONFIG;
  let app_list_file_path = &global_run_setup_config.app_list_file;
  init_global_site_list_config(app_list_file_path.as_str());
  let app_list_config = get_global_site_list_config();
  let app_site_config_vec = app_list_config.get_app_with_site_vec();
  let app_site_config_list = find_target_app_vec_by(&cmd_result.app_list, &app_site_config_vec);
  init_app_with_site_config_vec(app_site_config_list);
  if cmd_result.is_clear_cache {
    push_dev(
      format!("start clear cache")
    );
    let cache_dir = global_run_setup_config.log_cache.as_str();
    std::fs::remove_dir_all(cache_dir).expect("remove cache directory error");
  }
  let read_info = cmd_result.read_info;
  push_dev(format!("is readonly {}, read: [{:#?} - {:#?}]", read_info.is_read_only, read_info.read_after_date_option, read_info.read_before_date_option));
  let runtime = Runtime::new().expect("cannot create tokio::runtime::Runtime");
  if read_info.is_read_only {
    let result = start_read_log(
      read_info.read_after_date_option,
      read_info.read_before_date_option,
    );
    runtime.block_on(result);
  } else {
    let result = start_update_history_log();
    runtime.block_on(result);
  }
  write_default_log();
}
